<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Konva.js Draw Closed Shape</title>
  <script src="./konva.min.js"></script>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    #container {
      border: 1px solid black;
      margin: 10px;
      cursor: crosshair;
    }
  </style>
</head>

<body>

  <div id="container"></div>

  <script>
    // 创建舞台和图层
    var stage = new Konva.Stage({
      container: 'container',
      width: window.innerWidth - 200,
      height: window.innerHeight - 100,
    })

    var layer = new Konva.Layer()
    stage.add(layer)

    var isDrawing = false
    var currentLine

    stage.on('mousedown', function (e) {
      isDrawing = true
      var pos = stage.getPointerPosition()
      currentLine = new Konva.Line({
        points: [pos.x, pos.y],
        stroke: 'blue',
        strokeWidth: 3,
        lineCap: 'round',
        lineJoin: 'round',
        draggable: false
      })
      layer.add(currentLine)
    })

    stage.on('mousemove', function (e) {
      if (!isDrawing) return
      var pos = stage.getPointerPosition()

      // 检查是否超出舞台边界
      if (pos.x < 0 || pos.x > stage.width() || pos.y < 0 || pos.y > stage.height()) {
        isDrawing = false
        currentLine.closed(true) // 设置 closed 参数为 true，自动闭合图形
        layer.batchDraw()
        return
      }
      var newPoints = currentLine.points().concat([pos.x, pos.y])
      currentLine.points(newPoints)
      layer.batchDraw()
    })

    stage.on('mouseup', function (e) {
      if (!isDrawing) return
      isDrawing = false
      currentLine.closed(true) // 设置 closed 参数为 true，自动闭合图形
      layer.batchDraw()
    })

    stage.on("mouseleave", function (e) {
      if (!isDrawing) return
      isDrawing = false
      currentLine.closed(true) // 设置 closed 参数为 true，自动闭合图形
      layer.batchDraw()
    })
  </script>

</body>

</html>